# -*- coding: utf8 -*-

from plugmgr import plugin
import re, cPickle
__all__ = ['alias']

class alias(plugin):
    commands = ['add','show']
    requires = ['events','config','cmd']
    # TODO: personal, local and global aliases
    # TODO: priorities
    def handler(self,source,type,body,lang):
        for i in self.aliases:
            body = re.sub(i[0],i[1],body)
        return source,type,body,lang
    def __init__(self,bot):
        self.bot = bot
        self.bot["config"].setdefault('aliases', cPickle.dumps([]), 0, 100)
        self.aliases = cPickle.loads(str(self.bot["config"]["aliases"]))
        for i in self.commands:
            self.bot["cmd"].addHandler('alias_%s'%i,eval('self.cmd%s'%i))
    def connected(self):
        self.handlerId = self.bot['events'].registerHandler('message',self.handler,True)
    def disconnected(self):
        self.bot['events'].removeHandler('message',self.handlerId)
    def unload(self):
        for i in self.commands:
            self.bot["cmd"].removeHandler('alias_%s'%i)
    def cmdadd(self,c):
        args = c.args.lstrip().split('\n')
        self.aliases.append(args)
        self.bot["config"]['aliases'] = cPickle.dumps(self.aliases)
        c.reply(c._('Successful'))
    def cmdshow(self,c):
        c.reply('\n'.join('%s. %s'%(i[0]+1,' = '.join(i[1][:2])) for i in enumerate(self.aliases)))
    def cmddel(self,c):
        try:
            del self.aliases(int(c.args)-1)
            c.reply(c._('Successful'))
        except:
            c.reply(c._('Failed'))
        self.bot["config"]['aliases'] = cPickle.dumps(self.aliases)

